package com.dm.cloud.images.util;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.dm.cloud.basepo.service.SnowflakeGenId;
import com.dm.cloud.core.exception.CustomException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
@ConfigurationProperties(prefix = "dm.images.local")
@Data
public class LocalUtil {
    /**
     * 本地工作目录
     */
    private String workPath;
    /**
     * 发布服务IP地址
     */
    private String publicServerIp;
    /**
     * 发布服务端口
     */
    private Integer publicServerPort;
    /**
     * 对外发布的静态资源目录
     */
    private String publicSourcePath;

    private static File workDir;

    private static File publicSourceDir;

    private static File rwDataDir;

    private static File shardWork;

    private final SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmm");

    @PostConstruct
    public void init(){
        workDir=new File(workPath);
        if(!workDir.exists() || !workDir.isDirectory()){
            workDir.mkdirs();
        }
        publicSourceDir=new File(publicSourcePath);
        if(!publicSourceDir.exists() || !publicSourceDir.isDirectory()){
            publicSourceDir.mkdirs();
        }
        rwDataDir = new File(workDir.getAbsolutePath() + File.separator + "rwData");
        if(!rwDataDir.exists() || !rwDataDir.isDirectory()){
            rwDataDir.mkdirs();
        }
        shardWork = new File(workDir.getAbsolutePath() + File.separator + "shardWork");
        if(!shardWork.exists() || !shardWork.isDirectory()){
            shardWork.mkdirs();
        }

    }

    /**
     * 获取静态目录中的文件
     * @param fileName
     * @return
     */
    public static File getShardWork(String fileName){
        return new File(shardWork.getAbsolutePath()+ File.separator+fileName);
    }

    public static File getWorkFile(String fileName){
        return new File(workDir.getAbsolutePath()+ File.separator+fileName);
    }

    /**
     * 获取当前日期工作目录
     * @return
     */
    public File curDayDir(){
        File dir = new File(workDir.getAbsolutePath() + File.separator+"cache"+ File.separator + DateUtil.format(new Date(), "yyyy-MM-dd"));
        if(!dir.exists() || !dir.isDirectory()){
            dir.mkdirs();
        }
        return dir;
    }

    /**
     * 获取任务数据文件，在 static/rwData中。
     * @param filePath
     * @return
     */
    public File getRwDataFile(String filePath){
        String fileAbsPath=rwDataDir.getAbsolutePath()+File.separator +filePath;
        return new File(fileAbsPath);
    }

    /**
     * 上传任务数据文件
     * @param files
     * @return
     * @throws IOException
     */
    public String uploadRwDataFiles(MultipartFile[] files) throws IOException {
        String temp = SnowflakeGenId.genId() + "_" + format.format(new Date());
        String dir = rwDataDir.getAbsolutePath() + File.separator + temp;
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        for (MultipartFile file : files) {
            File targetFile = new File(dir, file.getOriginalFilename());
            file.transferTo(targetFile);
        }
        ZipUtil.zip(dirFile);
        deleteAllFile(dirFile);
        return temp + ".zip";
    }

    /**
     * 获取当前工作目录下的静态文件
     * @return
     */
    public File curFileDir(String fileName){
        File dir = new File(workDir.getAbsolutePath() + File.separator + fileName);
        if(!dir.exists()){
            dir.mkdirs();
        }
        return dir;
    }

    /**
     * 在当前日期工作目录中添加文件
     * @param fileName 在目录下继续添加的文件路径
     * @return
     */
    public File curDayWorkspaceAdd(String fileName) {
        String filePath=curDayDir().getAbsolutePath()+File.separator+fileName;
        File file = new File(filePath);
        if(!file.exists()){
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
//            file.createNewFile();
            try {
                Files.createFile(file.toPath());
            } catch (IOException e) {
                e.printStackTrace();
                throw new CustomException("创建文件["+file.getAbsolutePath()+"]失败！");
            }
        }
        return file;
    }

    /**
     * 获取静态目录文件的相对路径
     * @param fileAbsPath
     * @return
     */
    public String getRelativePath(String fileAbsPath){
        fileAbsPath=fileAbsPath.replace("\\","/");
        String workAbsPath=workDir.getAbsolutePath().replace("\\","/");
        if(fileAbsPath.startsWith(workAbsPath)){
            return fileAbsPath.substring(workAbsPath.length());
        }else{
            throw new CustomException("后台路径配置异常");
        }
    }

    public File getPublicSourceDir(){
        return publicSourceDir;
    }

    /**
     * 读取文件文本内容
     * @param detailsSnapshot
     * @return
     */
    public String readFileContent(String detailsSnapshot) {
        try {
            return IoUtil.read(new FileInputStream(
                            workDir.getAbsolutePath()+File.separator+detailsSnapshot),
                    Charset.forName("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 删除本地缓存文件
     * @param filePaths 文件相对路径列表
     */
    public void removeFileByRelativePaths(List<String> filePaths) {
        if(filePaths!=null && !filePaths.isEmpty()){
            for (String filePath : filePaths) {
                removeFileByRelativePath(filePath);
            }
        }
    }

    /**
     * 删除本地文件
     * @param path 文件相对路径
     */
    public boolean removeFileByRelativePath(String path) {
        if(StrUtil.isEmpty(path)){
            return false;
        }
        path=path.replace("\\","/");
        if(!path.startsWith("/")){
            path="/"+path;
        }
        try {
            File localFile=new File(getWorkPath()+path);
            if(localFile.exists() && localFile.isFile()){
                return localFile.delete();
            }else{
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public Charset getSystemEncoding(){
        String os = System.getProperty("os.name").toLowerCase();
        String charset;

        if (os.contains("win")) {
            // 如果是Windows系统，返回GBK编码
            charset = "GBK";
        } else {
            // 如果是Linux系统或其他系统，返回UTF-8编码
            charset = "UTF-8";
        }
        return Charset.forName(charset);
    }


    public void deleteAllFile(File from) {
        if (from.isDirectory()) {
            File[] files = from.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    deleteAllFile(file);
                }
            }
        }
        boolean delete = from.delete();
    }

}